package com.example.foods.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Utils {

    private static Logger logger = LoggerFactory.getLogger(Utils.class);

    private static MessageDigest messageDigest;

    private static SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy_MM_dd");
    private static SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private static int count = 0;
    private static Lock lock = new ReentrantLock();

    static {
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            logger.error("获取消息摘要实例时异常。" + e);
        }
    }


    /**
     * 将传入的密码明文进行摘要计算，返回摘要
     *
     * @param password
     * @return
     */
    public static String encodePassword(String password) {
        String result = null;
        try {
            if (password != null) {
                byte[] data = messageDigest.digest(password.getBytes("utf-8"));
                result = Base64.getEncoder().encodeToString(data);
            }
        } catch (Exception e) {
            logger.error("获取消息摘要实例时异常。" + e);
        }
        return result;
    }

    /**
     * 检查密码是否正确
     *
     * @param plainPwd   密码明文
     * @param encodedPwd 密码摘要
     * @return
     */
    public static boolean checkPassword(String plainPwd, String encodedPwd) {
        if (plainPwd == null || encodedPwd == null)
            return false;
        String digest = encodePassword(plainPwd);
        return digest.equals(encodedPwd);
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param length
     * @return
     */
    public static String generateRandomString(int length) {
        String str = "";
        for (int i = 0; i < length; i++) {
            if (Math.random() < 0.5) {
                //拼接随机的大写字母
                str += (char) (Math.random() * 26 + 'A');
            } else {
                //拼接随机的数字
                str += (int) (Math.random() * 10);
            }
        }
        return str;
    }

    /**
     * 生成 yyyy_MM_dd 格式的字符串
     *
     * @return
     */
    public static String generateSubDir() {
        return dateFormat1.format(new Date());
    }

    /**
     * 生成一个唯一的文件名
     *
     * @param fileName
     * @return
     */
    public static String generateUniqueFileName(String fileName) {
        lock.lock();
        String fileId = null;
        try {
            count++;
            if (count >= 100) {
                count = 0;
            }
            fileId = dateFormat2.format(new Date()) + String.format("%02d", count);
        } finally {
            lock.unlock();
        }
        int index = fileName.lastIndexOf(".");
        if (index >= 0) {
            fileId += fileName.substring(index);
        }
        return fileId;
    }
}
